/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 14:24:23
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;

public class JsonUtil {

	public static String pubInfoToJson(JSONObject pubInfo) {
		return pubInfoToJson(pubInfo, null, null);
	}
	
	public static String pubInfoToJson(JSONObject pubInfo, String num,  String areaCode) {

        try {
            if (pubInfo == null) {
                return "";
            }
            pubInfo.put("id", pubInfo.optString("pubId"));
            pubInfo.put("name", pubInfo.optString("pubName"));
            pubInfo.put("classifyName", pubInfo.optString("pubType"));
            pubInfo.put("weiboName", pubInfo.optString("weiBoName"));
            pubInfo.put("weiboUrl", pubInfo.optString("weiBoUrl"));
            pubInfo.put("weixin", pubInfo.optString("weiXin"));
            pubInfo.put("logo", pubInfo.optString("rectLogoName"));
            pubInfo.put("logoc", pubInfo.optString("circleLogoName"));
            pubInfo.put("website", pubInfo.optString("webSite"));

            JSONArray pubNumInfolist = pubInfo.optJSONArray("pubNumInfolist");

            /* SDK-502 zhaojiangwei 20160622 start */
            String numPurpose = null;
            boolean checkPurpose = false;
            if (!StringUtils.isNull(num) && !StringUtils.isNull(areaCode)) {
                checkPurpose = true;
            }
            /* SDK-502 zhaojiangwei 20160622 end */

            if (pubNumInfolist != null
                    && pubNumInfolist.length() > 0 ) {
                int size = pubNumInfolist.length();
                JSONArray jsonArray = new JSONArray();
                String optNum = "";
                String optAreaCode = "";
                for (int i = 0; i < size; i++) {
                    JSONObject pubNumInfo = (JSONObject)pubNumInfolist.get(i);
                      /* SDK-502 songzhiorong 20160623 start */
//                    if (String.valueOf(Constant.phone).equals(pubNumInfo.optString("type"))) {
                      /* SDK-502 songzhiorong 20160623 end */
                        JSONObject subObject = new JSONObject();
                        
                        /* SDK-502 zhaojiangwei 20160622 start */
                        optNum = pubNumInfo.optString("num");
                        optAreaCode = pubNumInfo.optString("areaCode");
                        /* SDK-502 huangzhiqiang 20160622 start */
                        if (checkPurpose && optAreaCode.contains(areaCode)) {
                            // 号码完全匹配或去除*后开头是匹配的
                            if (num.equals(optNum) || (optNum.contains("*") && num.startsWith(optNum.replace("*", "")))) {
                                numPurpose = pubNumInfo.optString("purpose");
                            }
                        }
                        /* SDK-502 huangzhiqiang 20160622 end */
                        /* SDK-502 zhaojiangwei 20160622 end */ 
                        
                        subObject.put("purpose", pubNumInfo.optString("purpose"));
                        subObject.put("num", optNum);
                        subObject.put("areaCode", optAreaCode);
                        subObject.put("extend", pubNumInfo.optString("extend"));
                        jsonArray.put(subObject);
                      /* SDK-502 songzhiorong 20160623 start */
//                    }
                      /* SDK-502 songzhiorong 20160623 end */

                }	 
                /* SDK-502 zhaojiangwei 20160622 start */
                if (!StringUtils.isNull(numPurpose)) {
                    pubInfo.put("purpose", numPurpose);
                }
                /* SDK-502 zhaojiangwei 20160622 end */

                pubInfo.put("pubnum", jsonArray);
            } else {
                pubInfo.put("pubnum", "");
            }

            pubInfo.remove("pubId");
            pubInfo.remove("pubName");
            pubInfo.remove("pubType");
            pubInfo.remove("pubTypeCode");
            pubInfo.remove("weiXin");
            pubInfo.remove("weiBoName");
            pubInfo.remove("weiBoUrl");
            pubInfo.remove("introduce");
            pubInfo.remove("address");
            pubInfo.remove("faxNum");
            pubInfo.remove("webSite");  
            pubInfo.remove("versionCode");   
            pubInfo.remove("email");
            pubInfo.remove("parentPubId");
            pubInfo.remove("slogan");            
            pubInfo.remove("rectLogoName");
            pubInfo.remove("circleLogoName");
            pubInfo.remove("extend");
            pubInfo.remove("pubNumInfolist");
            pubInfo.remove("loadMenuTime");
            pubInfo.remove("updateInfoTime");            
            pubInfo.remove("hasmenu");
            
            return pubInfo.toString();
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PubInfoToJson: ", e);
        }
        return "";
    }
	
    public static void putJsonToMap(JSONObject jsonObject,
            Map<String, String> valueMap) {
        try {
            if (jsonObject != null && valueMap != null) {
                Iterator iter = jsonObject.keys();
                while (iter.hasNext()) {
                    String jsonKey = (String) iter.next();
                    valueMap.put(jsonKey, jsonObject.getString(jsonKey));
                }
            }

        } catch (Throwable e) {
            // TODO: handle Throwable
        }
    }

    /**
     * 众JSON对象中获取值
     * 
     * @param data
     * @param key
     * @return
     */
    public static Object getValueFromJsonObject(JSONObject data, String key) {
        try {
            if (key != null && data != null && data.has(key)) {
                return data.get(key);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getValueFromJsonObject: ", e);

        }
        return null;
    }

    /**
     * 众JSON对象中获取值
     * 
     * @param data
     * @param key
     * @return
     */
    public static Object getValFromJsonObject(JSONObject data, String key) {
        try {
            if (key != null && data != null && data.has(key)) {
                return data.get(key);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getValueFromJsonObject: ", e);

        }
        return "";
    }

    /**
     * 将JSON字符串转换为 JSONObject
     * 
     * @param jsonStr
     *            字符串
     * @return JSONObject
     */
    public static JSONObject parseStrToJsonObject(String jsonStr) {
        JSONObject jsobj = null;
        if (!StringUtils.isNull(jsonStr)) {
            try {
                jsobj = new JSONObject(jsonStr.trim());
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "parseStrToJsonObject: ", e);

            }
        }
        return jsobj;
    }

    /**
     * 将JSON字符串转换为 JSONArray
     * 
     * @param jsonStr
     *            字符串
     * @return JSONArray
     */
    public static JSONArray parseStrToJsonArray(String jsonStr) {
        JSONArray jsonArray = null;
        if (!StringUtils.isNull(jsonStr)) {
            try {
                jsonArray = new JSONArray(jsonStr);
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "parseStrToJsonArray: ", e);

            }
        }
        return jsonArray;
    }

    /**
     * 将JSON对象有jsonKey有值时加入ContentValues
     * 
     * @param values
     * @param json
     * @param valueKey
     * @param jsonKey
     */
    public static void putJsonToConV(ContentValues values, JSONObject json,
            String valueKey, String jsonKey) {
        String str = json.optString(jsonKey);
        if (!StringUtils.isNull(str)) {
            values.put(valueKey, str);
        } else {
            values.remove(valueKey);
        }
    }

    /**
     * 依据key获取对应的数据
     * 
     * @param resultMap
     * @param key
     * @return
     */
    public static Object getValueWithMap(Map<String, Object> resultMap,
            String key) {
        try {
            if (resultMap != null && !resultMap.isEmpty()
                    && !StringUtils.isNull(key) && resultMap.containsKey(key)) {
                return resultMap.get(key);
            }

        } catch (Throwable e) {
        }
        return "";
    }

    /**
     * 返回json里的value，没有则返回默认字符串defaultStr
     * 
     * @param json
     * @param key
     * @param defaultStr
     * @return
     */
    public static String getValueFromJson(JSONObject json, String key,
            String defaultStr) {
        if (json != null) {
            try {
                String value = json.optString(key);
                return StringUtils.isNull(value) ? defaultStr : value;
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "getValueFromJson: ", e);

            }
        }
        return defaultStr;

    }

    /**
     * 把两个json对象合并，把第一个合并到第二个的后面
     * 
     * @param json1
     * @param json2
     */
    public static void JSONCombine(JSONObject json1, JSONObject json2) {
        try {
            if (json1 != null) {
                Iterator<String> it = json2.keys();
                String key = null;
                while (it.hasNext()) {
                    key = it.next();
                    json1.put(key, json2.get(key));
                }
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "JSONCombine: ", e);

        }
    }

  public static JSONObject getJsonObject(JSONObject jsonObject ,String... keyVals) {
        if (keyVals == null || jsonObject == null) {
            return null;
        }
        int len = keyVals.length;
        if (len == 0 || len % 2 != 0) {
            return null;
        }

        try {
            for (int i = 0; i < len;) {
                if (keyVals[i] != null && keyVals[i + 1] != null) {
                	jsonObject.put(keyVals[i], keyVals[i + 1]);
                }
                i = i + 2;
            }
            return jsonObject;
        } catch (JSONException e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getJsonObject: ", e);

        }
        return null;
    }
    
    public static JSONObject getJsonObject(String... keyVals) {
        if (keyVals == null) {
            return null;
        }
        int len = keyVals.length;
        if (len == 0 || len % 2 != 0) {
            return null;
        }

        try {
            JSONObject res = new JSONObject();
            for (int i = 0; i < len;) {
                if (keyVals[i] != null && keyVals[i + 1] != null) {
                    res.put(keyVals[i], keyVals[i + 1]);
                }
                i = i + 2;
            }
            return res;
        } catch (JSONException e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getJsonObject: ", e);

        }
        return null;
    }
    /*SDK-382 /songzhirong/2016.05.17---start---*/

    public static JSONObject changeMapToJason(Map<String, Object> result){
    	
    	try {
    		if(result==null || result.isEmpty())return null;
    		JSONObject jsonObject = new JSONObject(result);
        	return jsonObject;        

		} catch (Throwable e) {
            LogManager.e(Constant.TAG, "changeMapToJason: " , e);

		}
    	return null;        
        
    }
    
    public static String jsonObjectToString(JSONObject jsonObject){
    	try {
    		if(jsonObject!=null){
//    			String str = jsonObject.toString();
//    			if(withEscape){
//        			str = str.replace("\"", "\\\"");
//        			str = str.replace(":", ": ");
//        			
//    			}
//    			return str;
    			return jsonObject.toString();
    					
    		}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
    	return "";
    }
    /*SDK-382 /songzhirong/2016.05.17---end---*/
    
    /*SDK-447 /songzhirong/2016.05.20---start---*/
    public static Map<String, String> parseJSON2Map(String jsonStr){
        Map<String, String> map = new HashMap<String, String>();
    	try {    		
            JSONObject json = new JSONObject(jsonStr);
        	Iterator<?> it = json.keys();
			String key = "";
			String value = null;
			while (it.hasNext()) {// 遍历JSONObject
				key = (String) it.next().toString();
				value = json.optString(key);
				map.put(key, value);
			}		
            
		} catch (Throwable e) {
			// TODO: handle exception
		}       
        return map;
      }
    /*SDK-447 /songzhirong/2016.05.20---end---*/

    /* SDK-515 huangzhiqiang 20160629 start */
    public static JSONObject parseObjectToJson(Object obj) {
        try {
            if (obj == null) {
                return null;
            }
            JSONObject objJson = new JSONObject();
            Class<?> cls = obj.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                field.setAccessible(true);
                objJson.put(field.getName(), field.get(obj));
            }
            objJson.put("objectToJson", true);
            objJson.put("className", cls.getName());
            return objJson;
        } catch (Throwable e) {
//            LogManager.e(Constant.TAG, "parseObjectToJson obj:" + obj + " error:" + e.getMessage(), e);
        }
        return null;
    }
    /* SDK-515 huangzhiqiang 20160629 end */
    
    /* SDK-684 zhaojiangwei 20161124 start */ 
	public static String getStringValueFromJsonObject(JSONObject data, String key) {
		Object obj = getValueFromJsonObject(data, key);
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	public static long getLongValueFromJsonObject(JSONObject data, String key) {
		long value = 0;
		try {
			String str = getStringValueFromJsonObject(data, key);
			if (!StringUtils.isNull(str)) {
				value = Long.valueOf(str);
			}
		}
		catch (Throwable e) {
			// TODO: handle exception
		}
		return value;
	}
	/* SDK-684 zhaojiangwei 20161124 end */
}
